<?php
declare (strict_types=1);

namespace app\admin\controller\auth;

use app\common\controller\BaseController;
use app\admin\model\auth\Admin as AdminModel;
use think\exception\ValidateException;
use think\Validate;
use general\Random;

class Admin extends BaseController
{

    /**
     * @var AdminModel
     */
    protected $model;

    public function initialize()
    {
        parent::initialize();

        $this->model = new AdminModel;
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isGet()) {

            $filter = $this->request->param('filter/a', []);

            list($total, $list) = $this->model->getList($filter);
            foreach ($list as $row) {
                $groupList = $this->auth->getGroups($row['id']);
                $groupIds = [];
                foreach ($groupList as $k => $v) {
                    $groupIds[] = $v['id'];
                }
                $row->group = $groupIds;
            }
            $list->hidden(['password', 'salt']);
            $result = array("total" => $total, "items" => $list);

            return $this->success('请求成功', $result);
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                //模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    try {
                        $this->validate($params, $validate);
                        $validateRes = true;
                    } catch (ValidateException $e) {
                        // 验证失败 输出错误信息
                        $validateRes = $e->getError();
                    }
                    if ($validateRes !== true) {
                        return $this->error($validateRes);
                    }
                }
                if (!(new \think\Validate)->checkRule($params['password'], '\S{6,30}')) {
                    return $this->error(lang("Please input correct password"));
                }
                $params['salt'] = Random::alnum();
                $params['password'] = $this->auth->getEncryptPassword($params['password'], $params['salt']);

                $result = $this->model->save($params);
                if ($result !== false) {
                    $group = $this->request->post('group/a');
                    $this->model->setGroupAccess($group);
                    return $this->success('添加成功');
                } else {
                    return $this->error(lang('No rows were inserted'));
                }
            }
            return $this->error(lang('Parameter %s can not be empty', ''));
        }
    }

    /**
     * 编辑
     * @param null $id
     */
    public function edit($id = null)
    {
        $row = $this->model->find($id);
        if (!$row) {
            return $this->error(lang('No Results were found'));
        }
        if ($this->request->isPut()) {
            $params = $this->request->put();
            if ($params) {
                //模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    try {
                        $this->validate($params, $validate);
                        $validateRes = true;
                    } catch (ValidateException $e) {
                        // 验证失败 输出错误信息
                        $validateRes = $e->getError();
                    }
                    if ($validateRes !== true) {
                        return $this->error($validateRes);
                    }
                }
                if (isset($params['password']) && !empty($params['password'])) {
                    if (!(new \think\Validate)->checkRule($params['password'], '\S{6,30}')) {
                        return $this->error(lang("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = $this->auth->getEncryptPassword($params['password'], $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }
                $result = $row->save($params);
                if ($result !== false) {
                    $group = $this->request->post('group/a');
                    $row->setGroupAccess($group);
                    return $this->success('编辑成功');
                } else {
                    return $this->error(lang('No rows were updated'));
                }
            }
            return $this->error(lang('Parameter %s can not be empty', ''));
        }
    }

    /**
     * 删除
     * @param array $ids
     */
    public function del($ids = [])
    {
        if ($this->request->isDelete()) {
            $ids = $this->request->delete();
            if ($ids && is_array($ids)) {
                $pk = $this->model->getPk();
                $list = $this->model->where($pk, 'in', $ids)->select();
                $count = 0;
                foreach ($list as $k => $v) {
                    $v->delGroupAccess();
                    $count += $v->delete();
                }
                if ($count) {
                    return $this->success('删除成功');
                } else {
                    return $this->error(lang('No rows were deleted'));
                }
            }
            return $this->error(lang('Parameter %s can not be empty', 'id'));
        }
    }

}